package com.schoolvisitors.service;

import com.schoolvisitors.response.ResultBody;
import com.schoolvisitors.response.ResultCode;
import org.apache.commons.io.FilenameUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.schoolvisitors.utils.FileUtil.getMultipartFileMd5;

@Service
public class ImgService {
    private static final List<String> ALLOWED_TYPES = Arrays.asList("image/jpeg", "image/png");
    private static final long MAX_SIZE = 8 * 1024 * 1024; // 2MB
    private static final String UPLOAD_DIR = (System.getProperty("os.name").toLowerCase().contains("win")
            ? System.getenv("SystemDrive") + "/data/img/"
            : "/data/img/");

    public ResultBody uploadByImg(MultipartFile file){
        return upload(Arrays.asList("image/jpeg", "image/png"), file);
    }

    public ResultBody uploadByVideo(MultipartFile file){
        return upload(List.of("video/mp4"), file);
    }

    public ResultBody upload(List<String> allowedType, MultipartFile file) {
        if (file.isEmpty()) {
            return ResultBody.fail(ResultCode.FILE_EMPTY);
        }

        if (!allowedType.contains(file.getContentType())) {
            return ResultBody.fail(ResultCode.FILE_TYPE_ERROR);
        }

        if (file.getSize() > MAX_SIZE) {
            return ResultBody.fail(ResultCode.FILE_TOO_LARGE);
        }

        try {
            // 计算 MD5
            String fileMd5 = getMultipartFileMd5(file);
            String fileExt = FilenameUtils.getExtension(file.getOriginalFilename());
            String fileName = fileMd5 + "." + fileExt;

            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists() && !uploadDir.mkdirs()) {
                return ResultBody.fail(ResultCode.FILE_UPLOAD_ERROR);
            }

            File destFile = new File(uploadDir, fileName);

            // 如果已存在，不重新写入
            if (!destFile.exists()) {
                file.transferTo(destFile);
            }

            Map<String, String> data = Map.of(
                    "url", fileName
            );

            return ResultBody.success(data);

        } catch (IOException | NoSuchAlgorithmException e) {
            return ResultBody.fail(ResultCode.FILE_UPLOAD_ERROR);
        }
    }

    public ResponseEntity<byte[]> getImg(String filename){
        String ext = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();

        // 只允许jpg和png
        if (!ext.equals("jpg") && !ext.equals("png") && !ext.equals("jpeg")) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }

        File imgFile = new File(UPLOAD_DIR, filename);
        if (!imgFile.exists() || !imgFile.isFile()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }

        try (FileInputStream fis = new FileInputStream(imgFile)) {
            byte[] bytes = StreamUtils.copyToByteArray(fis);

            MediaType mediaType = ext.equals("png") ? MediaType.IMAGE_PNG : MediaType.IMAGE_JPEG;

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(mediaType);
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);

        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    public ResponseEntity<byte[]> getMedia(String filename) {
        String ext = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
        MediaType mediaType;

        switch (ext) {
            case "jpg":
            case "jpeg":
                mediaType = MediaType.IMAGE_JPEG;
                break;
            case "png":
                mediaType = MediaType.IMAGE_PNG;
                break;
            case "mp4":
                mediaType = MediaType.valueOf("video/mp4");
                break;
            default:
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }

        File mediaFile = new File(UPLOAD_DIR, filename);
        if (!mediaFile.exists() || !mediaFile.isFile()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }

        try (FileInputStream fis = new FileInputStream(mediaFile)) {
            byte[] bytes = StreamUtils.copyToByteArray(fis);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(mediaType);
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

}
